package com.rockbb.common.simpleframe.result;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.rockbb.common.simpleframe.config.SimpleConfig;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerProcessor {

	private static Logger logger = Logger.getLogger(FreeMarkerProcessor.class);
	private static Configuration cfg = initilize();

	private static Configuration initilize() 
	{
		Configuration config = new Configuration();
		config.setClassForTemplateLoading(FreeMarkerProcessor.class, SimpleConfig.getConfig("templates_path"));
		config.setDefaultEncoding(SimpleConfig.getConfig("encoding"));
		return config;
	}

	public static Configuration getConfiguration() 
	{
		return cfg;
	}

	public static String getStyle(int id) 
	{
		if (id >= 0 && id < SimpleConfig.getStyles().size()) 
		{
			return SimpleConfig.getStyles().get(id);
		} 
		else 
		{
			return SimpleConfig.getStyles().get(0);
		}
	}

	/**
	 * Note: the style ID is passed by root by key {ActionResult.MAP_KEY_STYLE}
	 * 
	 * @param res
	 * @param tpl_name
	 * @param root
	 */
	public static void process(HttpServletResponse res, String tpl_name, Map<String, Object> root) 
	{
		try
		{
			res.setContentType("text/html; charset=" + SimpleConfig.getConfig("encoding"));
			process(res.getWriter(), tpl_name, root);
		}
		catch (IOException e) 
		{
			logger.info("IOException");
			logger.debug("Exception details:", e);
		}
	}

	/**
	 * Note: the style ID is passed by root by key {ActionResult.MAP_KEY_STYLE}
	 * 
	 * @param writer
	 * @param tpl_name
	 * @param root
	 */
	public static void process(Writer writer, String tpl_name, Map<String, Object> root)
	{
		int styleId = 0;
		try
		{
			styleId = (Integer)root.get(ActionResult.MAP_KEY_STYLE);
		}
		catch(Exception e)
		{
			// do nothing
		}

		try
		{
			Template t = cfg.getTemplate(getStyle(styleId)+"/"+tpl_name);
			// 使用Environment 代替 Template.process, 是为了设置字符型变量的默认输出格式, 以免产生不必要的错误
			Environment env = t.createProcessingEnvironment(root, writer);
			//env.setLocale(java.util.Locale.CHINESE);
			env.setNumberFormat("#");
			env.process();
		}
		catch (TemplateException e) 
		{
			logger.info("TemplateException");
			logger.debug("Exception details:", e);
		}
		catch (IOException e) 
		{
			logger.info("IOException");
			logger.debug("Exception details:", e);
		}
		catch (Exception e)
		{
			logger.info("Unknown Exception, tpl name:"+tpl_name);
			logger.debug("Exception details:", e);
		}
	}
}